package org.istt.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.util.StrutsTypeConverter;
import org.apache.struts2.util.TextProviderHelper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.conversion.TypeConversionException;

public class DateConverter extends StrutsTypeConverter {
	protected final Log log = LogFactory.getLog(getClass());
	
	@Override
    public Object convertFromString(Map ctx, String[] value, Class arg2) {
        if (value[0] == null || value[0].trim().equals("")) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(getFormat());
        try {
            return sdf.parse(value[0]);
        } catch (ParseException pe) {
            throw new TypeConversionException("Invalid date!");
        }
    }
    
    protected String getFormat() {
    	String format = TextProviderHelper.getText("date.format", "dd/MM/yyyy", ActionContext.getContext().getValueStack());
    	if (log.isDebugEnabled()) {
    		log.debug("Format date object with pattern " + format);
    	}
    	return format;
    }
    
    @Override
    public String convertToString(Map ctx, Object data) {
        SimpleDateFormat sdf = new SimpleDateFormat(getFormat());
        return sdf.format(data);
    }
} 